<?php
class XA_Model_File extends XA_Model {


	public static function getLocation($id) {
		return self::loc($id);
	}


	public static function loc($id) {
		return FILE_REPOSITORY_PATH.self::getSubpath($id);
	}


	public static function getSubpath($id) {
		return self::sub($id);
	}


	public static function sub($id) {
		$file_padded_name = str_pad($id, 6, '0', STR_PAD_LEFT);
		return substr($file_padded_name, 0, 3).'/'.substr($file_padded_name, 3, 3);
	}


	public function add($name, $path) {
		if (is_readable($path)) {
			$file_id = xa::query("INSERT INTO `file` (`name`, `type`) VALUES ('".xa_db::esc($name)."', '')");
			$file_dir = dirname($file_save_path = $this->getLocation($file_id));
			if (!is_writable($file_dir)) {
				if (!mkdir($file_dir, 0777, true)) {
					trigger_error('Could not create directory '.$file_dir, E_USER_ERROR);
					die();
				}
			}
			if (is_uploaded_file($path)) {
				move_uploaded_file($path, $file_save_path);
			} else {
				copy($path, $file_save_path);
			}
			return $file_id;
		}
		return false;
	}


	public static function remove($id) {
		xa::query("DELETE FROM `file` WHERE `file_id` = ".intval($id)." LIMIT 1");
		if (file_exists(self::getLocation(intval($id)))) {
			unlink(self::getLocation(intval($id)));
		}
	}


	public function get($id) {
		$return = xa::query("SELECT * FROM `file` WHERE `file_id` = ".intval($id)." LIMIT 1")->row();
		$return['location'] = $this->getLocation($return['file_id']);
		return $return;
	}
}
